package com.zzwx.service.impl;

import com.zzwx.dao.dto.UserAndRoleDTO;
import com.zzwx.dao.entity.sys.*;
import com.zzwx.dao.mapper.sys.*;
import com.zzwx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserroleMapper userroleMapper;

    @Autowired
    private RolemenuMapper rolemenuMapper;

    @Autowired
    private MenuMapper menuMapper;

    public User findUserByName(String name){
        User user = new User();
        user.setName(name);
        return userMapper.selectOne(user);
    }

    @Override
    public List<User> findUsers() {
        return userMapper.selectAll();
    }

    public Role findRoleByName(String name){
        User user = this.findUserByName(name);
        return this.findRoleByUserId(user.getId());
    }

    @Override
    public List<Menu> findMenus() {
        return menuMapper.selectAll();
    }

    public Role findRoleByUserId(int userId){
        Userrole ur = new Userrole();
        ur.setUserId(userId);
        Userrole dbUr = userroleMapper.selectOne(ur);
        if(dbUr != null){
            Role role = new Role();
            role.setId(dbUr.getRoleId());
            return roleMapper.selectOne(role);
        }
        return null;
    }

    @Override
    public Menu findMenuById(int menuId) {
        Menu menu = new Menu();
        menu.setId(menuId);
        return menuMapper.selectOne(menu);
    }

    @Override
    public List<Rolemenu> findRolemenusByRoleId(int roleId) {
        Rolemenu rm = new Rolemenu();
        rm.setRoleId(roleId);
        return rolemenuMapper.select(rm);
    }

    @Override
    public List<UserAndRoleDTO> getUserAndRoles() {
        return userMapper.getUserAndRoles();
    }

    @Override
    public Set<String> findMenuByRoleId(int roleId) {
        List<Rolemenu> rms = this.findRolemenusByRoleId(roleId);
        Set<String> menus = new HashSet<>();
        if(rms != null && rms.size() > 0){
            for (Rolemenu rm : rms){
                Menu menu = new Menu();
                menu.setId(rm.getMenuId());
                Menu dbMenu = menuMapper.selectOne(menu);
                //menus.add(dbMenu.getMenuName());
                String url = dbMenu.getMenuUrl();
                if(!StringUtils.isEmpty(url)){
                    menus.add(dbMenu.getMenuUrl());
                    System.out.println(dbMenu.getMenuUrl());
                }
            }
        }
        return menus;
    }
}
